<?php

declare(strict_types=1);

namespace App\Controller;

use App\Library\RedisLib;
use App\Model\User;
use App\Request\LoginRequest;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\Di\Annotation\Inject;

use Hyperf\View\RenderInterface;


/**
 * @Controller()
 * Class WebSocketViewController
 * @package App\Controller
 */
class ChatController extends AbstractController
{

    /**
     * @Inject()
     * @var \Hyperf\Contract\SessionInterface
     */
    private $session;

    protected $redis;


    /**
     * @Inject()
     * @var RenderInterface
     */
    protected $render;

    /**
     * @GetMapping(path="index")
     * @param RequestInterface $request
     * @param ResponseInterface $response
     * @author github_sw <github_sw@yeah.net>
     */
    public function index(RequestInterface $request)
    {
        $token = $request->input('token');

        $user = RedisLib::getInstance()->get('User_token_' . $token, $default = null);


        if (!$user) {
            return $this->render->render('login');
        }
        $user     = json_decode($user, true);
        $hostName = 'ws://hyperfws.test';
        return $this->render->render('index', [
            'server' => $hostName,
            'token'  => $token,
            'user'   => $user
        ]);
    }


    /**
     * @RequestMapping(path="login",methods="get,post")
     * 登录
     */
    public function login(LoginRequest $request)
    {

        $params = $request->all();
        $user   = User::where('username', 'like','%'.$params['username'].'%')->first();
        if (!$user) {
            return $this->response->json([
                "code" => 10001,
                "data" => '',
                "msg"  => '用户不存在'
            ]);
        }

        if (!password_verify($params['password'], $user['password'])) {
            return $this->response->json([
                "code" => 10001,
                "data" => '',
                "msg"  => '密码输入不正确'
            ]);
        };

        $token = uniqid() . uniqid() . $user['id'];

        RedisLib::getInstance()->setex('User_token_' . $token, json_encode($user));

        RedisLib::getInstance()->setex('User_token_' . $token, json_encode($user),3600);

        return $this->response->json([
            "code" => 200,
            "data" => ['token' => $token],
            "msg"  => '登录成功'
        ]);
    }

    /**
     * @GetMapping(path="loginView")
     * @author github_sw <github_sw@yeah.net>
     */
    public function loginView()
    {
        return $this->render->render('login');
    }

    /**
     * @GetMapping(path="register")
     * 注册
     */
    public function register()
    {
        if ($this->request->getMethod() == 'POST') {

            $validate = new Validate();
            $validate->addColumn('username')->required('用户名必填');
            $validate->addColumn('password')->required('密码必填');
            $validate->addColumn('nickname')->required('昵称必填');
            $validate->addColumn('code')->required('验证码必填');

            if ($this->validate($validate)) {
                $params = $this->request()->getRequestParam();

                $RedisPool = Redis::defer('redis');
                $codeCache = $RedisPool->get('Code' . $params['key']);

                if ($codeCache != $params['code']) {
                    return $this->responseJson(10001, '验证码错误', $codeCache);
                }

                $UserModel = new UserModel();
                $user      = $UserModel->getUserByUsername($params['username']);
                if ($user) {
                    return $this->responseJson(10001, '用户名已存在');
                }

                $data = [
                    'avatar'   => $params['avatar'],
                    'status'   => $params['offline'],
                    'nickname' => $params['nickname'],
                    'username' => $params['username'],
                    'password' => password_hash($params['password'], PASSWORD_DEFAULT),
                    'sign'     => $params['sign'],
                ];

                $user_id = $UserModel->createUser($data);

                if (!$user_id) {
                    return $this->json(10001, '注册失败');
                }

                $FriendGroupModel = new FriendGroupModel();
                $FriendGroupModel->insertFriendGroup([
                    'user_id'   => $user_id,
                    'groupname' => '默认分组'
                ]);

                $GroupMemberModel = new GroupMemberModel();
                $GroupMemberModel->insertGroupMember([
                    'user_id'  => $user_id,
                    'group_id' => 10001
                ]);


                return $this->responseJson(200, '注册成功');
            } else {
                return $this->responseJson(10001, $validate->getError()->__toString(), 'fail');
            }
        } else {
            $code_hash = uniqid() . uniqid();
            $this->render->render('register',
                ['code_hash' => $code_hash]
            );
        }
    }


    /**
     * 验证码
     */
    public function getCode()
    {
        $params = $this->request()->getRequestParam();
        $key    = $params['key'] ?: 'code_img';

        $config = new Conf();
        $code   = new \EasySwoole\VerifyCode\VerifyCode($config);
        $num    = mt_rand(0000, 9999);
        $redis  = Redis::defer('redis');
        $redis->set('Code' . $key, $num, 1000);
        $this->response()->withHeader('Content-Type', 'image/png');
        $this->response()->write($code->DrawCode($num)->getImageByte());
    }
}
